// LAMEBuffer.cpp: implementation of the LAMEBuffer class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "LAMEBuffer.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LAMEBuffer buffer;

LAMEBuffer::LAMEBuffer() : LAMEBitmap()
{

}

LAMEBuffer::~LAMEBuffer()
{

}


void LAMEBuffer::addDirtyRect(LRect &r)
{
	for (int i=0; i<rects.count(); i++)
	{
		if (rects[i].isRectInside(r)) 
			return; //don't have to copy this rect, it's already covered for
	}
	if (r.x < 0)         {r.w += r.x; r.x = 0;}
	if (r.y < 0)         {r.h += r.y; r.y = 0;}
	if (r.x + r.w > w) {r.w += (w - r.x - r.w);}
	if (r.y + r.h > h) {r.h += (h - r.y - r.h);}
	rects.add(&r);

}


void LAMEBuffer::copy()
{

}

void expand16to32(short16 *source, int32 *dest, int num)
{
	__asm
	{
		mov edi,dest
		mov esi,source
		mov ecx,num
conv16_loop:
		movzx eax,short ptr[esi]
		mov ebx,eax
		mov edx,eax

		and eax,0x001F
		and ebx,0x07E0
		and edx,0xF800

		shl eax,3
		shl ebx,5
		or eax,ebx
		shl edx,8
		or eax,edx

		mov [edi],eax

		add esi,2
		add edi,4
		dec ecx
		jnz conv16_loop
	}
}


void LAMEBuffer::copyW32(int32 *buf)
{
	if (rects.count()==0) return;

	if (!buf) {
		rects.empty();
		return;
	}

	for (int i=0; i<rects.count(); i++)
	{
		LRect &r = rects[i];
		for (int y=r.y; y<r.y+r.h; y++)
		{
			int32 *d = buf + y*w + r.x;
			short16 *s = data + y*w + r.x;

			if (r.w>0) 
				expand16to32(s,d,r.w);
		}
	}
	rects.empty();
}

